package com.cos66.asynctask;

import java.io.File;
import java.io.InputStream;

import android.os.Handler;
import android.os.Message;

import com.cos66.intf.ErrorCallBack;
import com.cos66.intf.FileCallBack;
import com.cos66.utils.Cos66Setting;
import com.cos66.utils.FileUtils;
import com.cos66.utils.HttpUtils;

public class ListAsyncTask {

	private String FilePath;
	private String FileName;

	
	private static final int ERROR_MESSAGE = 0;
	private static final int SUCCEED_MESSAGE = 1;

	public ListAsyncTask(String FilePath, String FileName) {
		this.FileName = FileName;
		this.FilePath = FilePath;
	}

	public void LoadList(final String URL, final FileCallBack fileCallBack,
			final ErrorCallBack errorCallBack) {

		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case ERROR_MESSAGE:
					errorCallBack.ErrorShow((String) msg.obj);
					break;
				case SUCCEED_MESSAGE:
					fileCallBack.onFileCreate((File) msg.obj);
					break;
				}
			}

		};

		new Thread() {

			@Override
			public void run() {
				InputStream inputStream = HttpUtils.queryStringForGet(URL);
				if (inputStream == null) {
					Message message = handler.obtainMessage(ERROR_MESSAGE,
							Cos66Setting.SERVICE_ERROR);
					handler.sendMessage(message);
				} else {
					File file = FileUtils.WriteIStoFile(FilePath, FileName,
							inputStream);
					Message message = handler.obtainMessage(SUCCEED_MESSAGE,
							file);
					handler.sendMessage(message);
				}
			}

		}.start();
	}

}
